app.controller('UserCtrl', function ($scope, $log, $location) {

    var loadUsers = function (page) {
        restClient.users.read({page: page}).done(function (data) {
            $scope.users = data.content;
            $scope.page = data.page;
            $scope.$apply();
        });
    }

    loadUsers(0);

    $scope.previousPage = function () {
        loadUsers($scope.page.number - 1);
    }

    $scope.nextPage = function () {
        loadUsers($scope.page.number + 1);
    }

    $scope.addUser = function () {
        $scope.add = {};
        $("#add-user").modal("show");
    }

    $scope.confirmAdd = function () {
        var request = restClient.users.create($scope.add);
        request.complete(function (data) {
            if (data.status == 201) {
                toastr.success('Add user succeed');
                loadUsers($scope.page.number);
                $("#add-user").modal("hide");
            } else {
                toastr.error('Add user failed, ' + data.responseJSON[0]);
            }
        });
    }

    $scope.editUser = function (user) {

        $scope.edit = angular.copy(user);
        $("#edit-user").modal("show");

    };

    $scope.confirmEdit = function () {

        var request = restClient.users.patch($scope.edit.id, $scope.edit);
        request.complete(function (data) {
            if (data.status == 200) {
                toastr.success('Update user succeed');
                loadUsers($scope.page.number);
                $("#edit-user").modal("hide");
            } else {
                toastr.error('Update user failed, ' + data.responseJSON[0]);
            }
        });
    }

    $scope.deleteUser = function (user) {
        bootbox.confirm("Are you sure want to delete user: " + user.name, function (result) {
            if (result == true) {
                var request = restClient.users.delete(user.id);
                request.complete(function (data) {
                    if (data.status == 200) {
                        toastr.success('Delete succeed');
                        loadUsers($scope.page.number);
                    } else {
                        toastr.error('Delete failed');
                    }
                });
            }
        })
    };
});

